<?php
$cs = Yii::app()->clientScript;

$this->breadcrumbs=array(
	'Page'=>array('/Cms/admin/page'),
    'Revision'=>array('/Cms/admin/pageRevision', 'page_id'=>$model->page_id),
	'Manage',
);

$script = "
jQuery('#content').delegate('.button-column a.view', 'click', function(){
    var url = jQuery(this).attr('href');
    jQuery.fancybox({
        'titleShow'         : false,
        'height'            : '100%',
        'width'             : '100%',
        'autoScale'         : true,
        'transitionIn'      : 'none',
        'transitionOut'     : 'none',
        'type'              : 'iframe',
        'href'              : url
    });
    return false;
});
";
$cs->registerScript(__CLASS__.'#Preview', $script);

$script = "
jQuery.new_revision_url = '';
jQuery('#content').delegate('.button-column a.new-revision', 'click', function(){
    jQuery.new_revision_url = jQuery(this).attr('href');
    jQuery('#new-revision-form form').get(0).reset();
    jQuery.fancybox({
        'type' : 'inline',
        'href' : '#new-revision-form',
        'autoScale'     : false,
        'titleShow'     : false,
        'width'         : 398,
        'model'         : true
    });
    return false;
});
jQuery('body').delegate('#fancybox-content .cancel', 'click', function(){
    jQuery.fancybox.close();
    return false;
});
jQuery('body').delegate('#fancybox-content .create-new-revision', 'click', function(){
    var log = jQuery('#fancybox-content textarea').val();
    jQuery.get(jQuery.new_revision_url, {'log' : log}, function(){
        jQuery.fn.yiiGridView.update('page-revision-grid');
        jQuery.fancybox.close();
    });
    return false;
});
";
$cs->registerScript(__CLASS__.'#NewRevision', $script);

$script = "
var old_workflow_id = [];
jQuery.fn.set_active_workflows = function(cell){
    jQuery('#available-workflows input').attr('checked', false);
    jQuery('#current_revision').val(jQuery(cell).prevAll('td:last').text());
    jQuery('#available-workflows input').removeAttr('disabled');
    old_workflow_id = [];
    jQuery.each(jQuery('span', cell), function(){
        var id = parseInt(jQuery(this).attr('id').replace('workflow-', ''));
        var obj = jQuery('#available-workflows input[value=\"'+id+'\"]');
        obj.attr('checked', true);
        //must have least one revision active in Initial Workflow
        if (id == {$initialWorkflowId})
            obj.attr('disabled', 'disabled');
        old_workflow_id.push(id);
    });
};
jQuery('#content').delegate('.active-workflow-column a', 'click', function(){
    $('#page-tabs').tabs('select',3);
    var revsision = $(this).attr('href').replace('#','');
    $('#workflow-grid .filters select').val(revsision).trigger('change');
    return false;
});

jQuery('#available-workflows-wrapper .cancel').click(function(){
    jQuery.fancybox.close();
    return false;
});
jQuery('#available-workflows-wrapper .apply').click(function(){
    var url = jQuery(this).attr('href');
    var revision = jQuery('#current_revision').val();
    var workflow_ids = [];
    jQuery.each(jQuery('#available-workflows input:checked'), function(){
        workflow_ids.push(jQuery(this).val());
    });
    jQuery.fancybox.showActivity();
    jQuery.get(url, {'revision' : revision, 'workflow_id' : workflow_ids, 'old_workflow_id' : old_workflow_id}, jQuery.proxy(function(data){
        data = eval(data);
        if (data.status != undefined && data.status)
        {
            jQuery.fn.yiiGridView.update('page-revision-grid');
            //reload workflows
            if (jQuery('#ui-tabs-3 .grid-view').size())
                jQuery('#page-tabs').tabs('load', 3);
        }
        jQuery.fancybox.hideActivity();
    }, this));
    return false;
});
";
$cs->registerScript('RevertPage', $script);
?>

<?php
$baseScriptUrl=Yii::app()->getAssetManager()->publish(Yii::getPathOfAlias('zii.widgets.assets')).'/gridview';
$columns = array(
    array(
        'header'=>'Revision',
        'name'=>'id',
        'htmlOptions'=>array('width'=>'3%', 'align'=>'center'),
    ),
    array(
        'header'=>'Template',
        'name'=>'template_content_id',
        'type'=>'raw',
        'value'=>'is_object($data->templateContent) && is_object($data->templateContent->template) ? CHtml::link($data->templateContent->template->name." - rev#".$data->templateContent->revision_id, array("/Cms/admin/template/update", "id"=>$data->templateContent->template_id, "revision_id"=>$data->templateContent->revision_id, "page_id"=>$data->page_id, "page_revision"=>$data->id), array("title"=>"Edit ".$data->templateContent->template->name." - rev#".$data->templateContent->revision_id)) : ""',
    ),
    array(
        'name'=>'log',
        'type'=>'raw',
        'value'=>'"<div><span>".$data->log."</span> ".CHtml::link(CHtml::image("'.$baseScriptUrl.'/update.png", ""), array("editLog", "revision_id"=>$data->id, "page_id"=>$data->page_id), array("class"=>"edit-log", "title"=>"Edit Log"))."</div>"',
    ),
    array(
        'name'=>'last_update',
        'value'=>'(is_object($data->updatedBy) ? $data->updatedBy->username : "")."<br />".Yii::app()->getDateFormatter()->formatDateTime(strtotime($data->last_update))',
        'type'=>'html',
        'filter'=>false,
        'htmlOptions'=>array(
            'class'=>'datetime-column'
        )
    ),
    array(
        'name'=>'creation_datetime',
        'value'=>'(is_object($data->createdBy) ? $data->createdBy->username : "")."<br />".Yii::app()->getDateFormatter()->formatDateTime(strtotime($data->creation_datetime))',
        'type'=>'html',
        'filter'=>false,
        'htmlOptions'=>array(
            'class'=>'datetime-column'
        )
    ),
    array(
        'header'=>'Active Workflows',
        'name'=>'id',
        'type'=>'raw',
        'value'=>'CHtml::link("Change", "#".$data->id)',
        'htmlOptions'=>array(
            'class'=>'active-workflow-column',
        ),
        'headerHtmlOptions'=>array('style'=>'width:130px;'),
        'filter'=>false,
    ),
    array(
        'class'=>'CButtonColumn',
        'template'=>'{deleteRevision} {customize} {copy} {preview} {new_revision} {goto}',
        'viewButtonUrl'=>'is_object($data->page) && is_object($data->page->defaultUrl) ? "http://".trim($data->initialWorkflowUrl, "/")."/".trim($data->page->defaultUrl->url, "/")."?preview=1&revision=".$data->id : "#"',
        'viewButtonOptions'=>array(
            'title'=>'Preview',
            'class'=>'view',
        ),
        'buttons'=>array(
            'preview'=>array(
                'label'=>'Preview',
                'imageUrl'=>$baseScriptUrl.'/view.png',
                'url'=>'is_object($data->page) && is_object($data->page->defaultUrl) ? Yii::app()->request->hostInfo."/".trim($data->page->defaultUrl->url, "/")."?preview=1&revision=".$data->id : "#"',
                'options'=>array('class'=>'view'),
                'visible'=>'Yii::app()->request->getQuery("layout", "") !== "popup"',
            ),
            'new_revision'=>array(
                'label'=>'New Revision',
                'imageUrl'=>Yii::app()->theme->baseUrl.'/images/new_revision.png',
                'url'=>'Yii::app()->controller->createUrl("/Core/service/ajax", array("SID"=>"Cms.PageRevision.copy","source_site_id"=>Yii::app()->cmsManager->site["id"],"target_site_id"=>Yii::app()->cmsManager->site["id"],"source_page_id"=>$data->page_id,"target_page_id"=>$data->page_id,"copy_revision"=>$data->id,"active_workflow"=>false,"link_data"=>false))',
                'options'=>array('class'=>'new-revision'),
            ),
            'goto'=>array(
                'label'=>'Go to',
                'imageUrl'=>Yii::app()->theme->baseUrl.'/images/link-go.png',
                'url'=>'is_object($data->page) && is_object($data->page->defaultUrl) ? Yii::app()->request->hostInfo."/".trim($data->page->defaultUrl->url, "/")."?revision=".$data->id : "#"',
                'options'=>array('target'=>'_blank'),
            ),
            'copy'=>array(
                'label'=>'Copy',
                'imageUrl'=>Yii::app()->theme->baseUrl.'/images/copy-page.png',
                'url'=>'"#".$data->id',
                'options'=>array(
                    'class'=>'copy',
                ),
            ),
            'deleteRevision'=>array(
                'label'=>'Delete',
                'imageUrl'=>$baseScriptUrl.'/delete.png',
                'url'=>'Yii::app()->controller->createUrl("/Cms/admin/pageRevision/delete", array("id[id]"=>$data->id, "id[page_id]"=>$data->page_id))',
                'options'=>array('class'=>'delete'),
                'visible'=>'count($data->getActiveWorkflows()) <= 0',
            ),
            'customize'=>array(
                'label'=>'Customize',
                'imageUrl'=>$baseScriptUrl.'/update.png',
                'url'=>'Yii::app()->controller->createUrl("template", array("revision_id"=>$data->id, "page_id"=>$data->page_id))',
                'options'=>array(
                    'title'=>'Change template, override CSS/JS files, edit page content',
                )
            )
        ),
        'headerHtmlOptions'=>array(
            'style'=>'width:110px;',
        ),
        'htmlOptions'=>array(
            'class'=>'actions-column button-column',
            'style'=>'text-align:center;',
        )
    )
);

$grid = $this->widget('zii.widgets.grid.CGridView', array(
	'id'=>'page-revision-grid',
	'dataProvider'=>$model->search(),
    'enableSorting'=>false,
	'filter'=>$model,
	'columns'=>$columns,
    'afterAjaxUpdate'=>'js:function(){jQuery.fancybox.close();}',
));

$script = "
jQuery.delete_link = '';
jQuery('.button-column .delete').live('click', function(){//Are you sure you want to delete this item?
    jQuery.delete_link = jQuery(this).attr('href');
    jQuery.fancybox({
        'type' : 'inline',
        'href' : '#delete-revision',
        'autoScale'     : false,
        'titleShow'     : false,
        'width'         : 398,
        'model'         : true
    });
    return false;
});

jQuery('.delete-revision').live('click', function(){
    if(!confirm('Are you sure you want to delete this item?')) return false;
    
    jQuery.fancybox.close();
    var delete_template = jQuery('#fancybox-content #delete_template').attr('checked') ? 1 : 0;
    var delete_widget_data = jQuery('#fancybox-content #delete_widget_data').attr('checked') ? 1 : 0;
    jQuery.get(jQuery.delete_link, {delete_template : delete_template, delete_widget_data : delete_widget_data}, function(){
        jQuery.fn.yiiGridView.update('page-revision-grid');
    });
    return false;
});
";
$cs->registerScript(__CLASS__.'#DeleteRevision', $script);

$script = "
jQuery.edit_log_link = '';
jQuery('.edit-log').live('click', function(){
    jQuery.edit_log_link = jQuery(this).attr('href');
    jQuery('#edit-log textarea').val(jQuery(this).prev('span').text());
    jQuery.fancybox({
        'type' : 'inline',
        'href' : '#edit-log',
        'autoScale'     : false,
        'titleShow'     : false,
        'hideOnOverlayClick'     : false,
        'width'         : 398,
        'model'         : true
    });
    return false;
});

jQuery('#edit-log .save-log').live('click', function(){
    jQuery.fancybox.close();
    var data = jQuery('#edit-log textarea').val();
    jQuery.post(jQuery.edit_log_link, {data : data}, function(){
        jQuery.fn.yiiGridView.update('page-revision-grid');
    });
    return false;
});
";
$cs->registerScript(__CLASS__.'#EditLog', $script);
?>
<div id="available-workflows-wrapper" style="display: none;">
    <div id="available-workflows" style="width: 300px;">
        <div>
            Choose the workflows that this revision will be active for
            <div class="list" style="margin-left: 15px;">
                <?php echo CHtml::checkBoxList('workflow', '', $workflows);?>
            </div>
        </div>
        <div align="right">
            <?php echo CHtml::hiddenField('current_revision', '');?>
            <?php echo CHtml::link('Cancel', '#', array('class'=>'cancel'));?>
            <?php echo CHtml::link('Apply', array('/Core/service/ajax', 'SID'=>'Cms.pageRevision.activeWorkflow', 'page_id'=>$model->page_id), array('class'=>'apply'));?>
        </div>
    </div>
</div>
<div style="display: none;">
    <div id="new-revision-form" style="width: 398px;">
    <?php echo CHtml::beginForm('');?>
    <?php echo CHtml::label('Message', 'new_revision_log');?>:
    <?php echo CHtml::textArea('new_revision_log', '', array('cols'=>70,'rows'=>7));?>
    <div align="right">
        <?php echo CHtml::button('Cancel', array('class'=>'cancel'));?>
        <?php echo CHtml::button('Create new revision', array('class'=>'create-new-revision'));?>
    </div>
    <?php echo CHtml::endForm();?>
    </div>
</div>
<div style="display: none;">
    <div id="delete-revision" style="width: 398px;">
        <div><?php echo CHtml::checkBox('delete_template');?> <?php echo CHtml::label('Delete related template if not used anywhere else', 'delete_template');?></div>
        <div><?php echo CHtml::checkBox('delete_widget_data');?> <?php echo CHtml::label('Delete widgets if not used anywhere else', 'delete_widget_data');?></div>
        <div align="right">
            <?php echo CHtml::button('Cancel', array('class'=>'cancel'));?>
            <?php echo CHtml::button('Delete', array('class'=>'delete-revision'));?>
        </div>
    </div>
</div>
<div style="display: none;">
    <div id="edit-log" style="width: 398px;">
        <div><?php echo CHtml::textArea('log', '', array('cols'=>70, 'rows'=>7));?></div>
        <div align="right">
            <?php echo CHtml::button('Cancel', array('class'=>'cancel'));?>
            <?php echo CHtml::button('Save', array('class'=>'save-log'));?>
        </div>
    </div>
</div>